from OWRpy import * 
import redRi18n
_ = redRi18n.get_(package = 'metaanalysis')



import signals
import redRGUI
#signal classes
#from libraries.base.signalClasses.RDataFrame import RDataFrame as redRRDataFrame
#from libraries.base.signalClasses.StructuredDict import StructuredDict as redRStructuredDict
#from libraries.base.signalClasses.UnstructuredDict import UnstructuredDict as redRUnstructuredDict


#Qt widgets
#from libraries.base.qtWidgets.lineEdit import lineEdit as redRlineEdit
#from libraries.base.qtWidgets.tabWidget import tabWidget as redRtabWidget
#from libraries.base.qtWidgets.checkBox import checkBox as redRcheckBox
#from libraries.base.qtWidgets.listBox import listBox as redRlistBox
#from libraries.base.qtWidgets.groupBox import groupBox as redRgroupBox
#from libraries.base.qtWidgets.spinBox import spinBox as redRspinBox
#from libraries.base.qtWidgets.comboBox import comboBox as redRcomboBox
#from libraries.base.qtWidgets.widgetBox import widgetBox as redRwidgetBox
#from libraries.base.qtWidgets.widgetLabel import widgetLabel as redRwidgetLabel
#from libraries.plotting.qtWidgets.redRPlot import redRPlot # for color picket, does not work


class metacontTable(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.require_librarys(["meta"])
        self.setRvariableNames(["metacontTable"])
        self.data = {}

        # Python variables
        self.data = {}
        self.RFunctionParam_object = ''
        self.metacon_TCList=[]
        self.metacon_studyList=[]
        self.metacont_Group = []
        
        #Inputs
#<<<<<<< .mine
        #self.inputs.addInput("X", "X", redRRDataFrame, self.processobject)
#=======
        self.inputs.addInput("X", "X", signals.base.RDataFrame, self.processobject) # create a new signal
#>>>>>>> .r142
        
        #Outputs
#<<<<<<< .mine
        #self.outputs.addOutput("Metacont table","Metacont table", redRStructuredDict) #export a dataframe through dict?
#=======
        self.outputs.addOutput("Metacont table","Metacont table", signals.base.StructuredDict) #
#>>>>>>> .r142

        # GUI
        self.metacont_studyColumn = redRGUI.base.comboBox(self.controlArea, label = 'Study column')
        #self.metacont_Group = redRlineEdit(self.controlArea, label = "Study groups (optional):", text = '[]')
        self.metacont_GroupText = redRGUI.base.widgetLabel(self.controlArea, label = (''.join(self.metacon_studyList)))
        self.metacont_TCColumn = redRGUI.base.comboBox(self.controlArea, label = 'Treatment / control column', callback=self.onTCColumnChange)        
        self.metacont_TCbox = redRGUI.base.widgetBox(self.controlArea, orientation='horizontal')      
        self.metacont_treatmentFactor = redRGUI.base.checkBox(self.metacont_TCbox,  label = "Treatment tag", buttons = self.metacon_TCList)
        self.metacont_controlFactor = redRGUI.base.checkBox(self.metacont_TCbox,  label = "Control tag", buttons = self.metacon_TCList)        
        self.metacont_varColumn = redRGUI.base.comboBox(self.controlArea, label = 'Variable column')
        self.metacont_TCbox.hide()
        
        # Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)


        
        
    def onTCColumnChange(self):
        self.metacon_TCList = self.R('levels(factor('+unicode(self.RFunctionParam_object)+'$'+unicode(self.metacont_TCColumn.currentId())+'))')
        #self.metacont_treatmentFactor.clear()
        #self.metacont_controlFactor.clear()
        self.metacont_treatmentFactor.addButtons(self.metacon_TCList)
        self.metacont_controlFactor.addButtons(self.metacon_TCList)
        
    def processobject(self, data):
        
        if data:
            self.RFunctionParam_object=data.getData()
            self.data = data
            self.metacont_studyColumn.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            self.metacont_TCColumn.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            self.metacont_varColumn.update(self.R('names('+self.RFunctionParam_object+')', wantType = 'list'))
            self.metacont_TCbox.show()
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_object=''
            
        
    def commitFunction(self):
        if str(self.RFunctionParam_object) == '':
            self.status.setText('No data')
            return
        
        if self.metacont_treatmentFactor.getCheckedIds() == []: 
            self.status.setText('Select one or more tags to identify treatment data')
            return
        else:
           self.metacont_treatmentList = self.metacont_treatmentFactor.getCheckedIds()
        if self.metacont_controlFactor.getCheckedIds() == []: 
            self.status.setText('Select one or more tags to identify control data')
            return
        else:
           self.metacont_controlList = self.metacont_controlFactor.getCheckedIds()
           
        self.R('studyList<-levels(factor('+unicode(self.RFunctionParam_object)+'$'+unicode(self.metacont_studyColumn.currentId())+'))')
        self.R('meane<-vector();sde<-vector();ne<-vector();meanc<-vector();sdc<-vector();nc<-vector()')
        
        for i in range(1,self.R('length(studyList)')):
            self.R('subtable<-'+unicode(self.RFunctionParam_object)+'['+unicode(self.RFunctionParam_object)+'$'+unicode(self.metacont_studyColumn.currentId())+'==studyList['+str(i)+'],]')
            
            # treatment data
            self.R('tmp<-vector()')
            for j in range(0,len(self.metacont_treatmentList)):
                treatment=self.metacont_treatmentList[j]
                self.R('tmp['+str(j+1)+']<-subtable$'+unicode(self.metacont_TCColumn.currentId())+'=="'+treatment+'"')
            ##################
            inj = ' | '.join(string)
            self.R('treated<-subtable['+inj+',]')
            meane.append(self.R('mean(treated$'+unicode(self.metacont_varColumn.currentId())+')'))
            sde.append(self.R('sd(treated$'+unicode(self.metacont_varColumn.currentId())+')'))
            ne.append(self.R('nrow(treated)'))
            
            # control data
            string=[]
            for control in self.metacont_controlList:
                string.append('subtable$'+unicode(self.metacont_TCColumn.currentId())+'=="'+control+'"')
            inj = ' | '.join(string)
            self.R('controled<-subtable['+inj+',]')
            meanc.append(self.R('mean(controled$'+unicode(self.metacont_varColumn.currentId())+')'))
            sdc.append(self.R('sd(controled$'+unicode(self.metacont_varColumn.currentId())+')'))
            nc.append(self.R('nrow(controled)'))
        
        metacontDict = {'Study':self.metacont_studyList,'mean.e':meane,'sd.e':sde,'n.e':ne,'mean.c':meanc,'sd.c':sdc,'n.c':nc} # add group column
        newMetacontTable = signals.base.StructuredDict(self, data = metacontDict)
        self.rSend("Metacont table", newMetacontTable)